import { useState } from 'react';
import { Card, Divider, Switch } from 'antd';
import {
	DndContext,
	closestCenter,
	KeyboardSensor,
	PointerSensor,
	useSensor,
	useSensors,
	type DragEndEvent,
	type UniqueIdentifier
} from '@dnd-kit/core';
import {
	arrayMove,
	SortableContext,
	sortableKeyboardCoordinates,
	rectSortingStrategy
} from '@dnd-kit/sortable';
import { GridContentStyle } from '../style';
import SortableItem from './SortableItem';

function SortTable() {
	const [isSort, setIsSort] = useState(false);

	const [items, setItems] = useState<
		{
			id: UniqueIdentifier;
			name: string;
		}[]
	>([
		{ id: 1, name: 'aaa' },
		{ id: 2, name: 'bbb' },
		{ id: 3, name: 'ccc' },
		{ id: 4, name: 'ddd' },
		{ id: 5, name: 'eee' },
		{ id: 6, name: 'fff' },
		{ id: 7, name: 'ggg' }
	]);
	const sensors = useSensors(
		useSensor(PointerSensor),
		useSensor(KeyboardSensor, {
			coordinateGetter: sortableKeyboardCoordinates
		})
	);

	function handleDragEnd(event: DragEndEvent) {
		const { active, over } = event;
		if (active.id !== over.id) {
			setItems((items) => {
				const oldIndex = items.findIndex((item) => item.id === active.id);
				const newIndex = items.findIndex((item) => item.id === over.id);

				return arrayMove(items, oldIndex, newIndex);
			});
		}
	}

	return (
		<Card>
			<Switch
				checkedChildren="开启"
				unCheckedChildren="关闭"
				checked={isSort}
				onChange={setIsSort}
			/>
			<Divider />
			<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
				<SortableContext items={items} strategy={rectSortingStrategy}>
					<GridContentStyle>
						{items.map((item) => (
							<SortableItem key={item.id} id={item.id} disabled={!isSort}>
								{item.name}
							</SortableItem>
						))}
					</GridContentStyle>
				</SortableContext>
			</DndContext>
		</Card>
	);
}

export default SortTable;
